<?php

namespace App\Jobs\College;

use App\Models\College\CollegeTrainingOrderModel;
use App\Models\College\CollegeTrainingOrderUserModel;
use App\Models\College\CollegeTrainingPlanModel;
use App\Remote\Feishu\FeishuMsgRemote;
use App\Remote\Rms\RmsShopRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class FinishTrainingOrderJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $orderId;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(int $orderId)
    {
        $this->orderId = $orderId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            self::handleTask($this->orderId);
        } catch (\Exception $exception) {
            logException("培训单完成通知飞书消息 {$this->orderId}", $exception, ["orderId" => $this->orderId], true, true);
        }
    }

    public static function handleTask(int $orderId)
    {
        $trainingPlan = CollegeTrainingPlanModel::query()
                                                ->whereHas("orderRel", function ($query) use ($orderId) {
                                                    return $query->where("id", $orderId);
                                                })
                                                ->with([
                                                    "orderRel" => function ($query) {
                                                        $query->with([
                                                            "resourceFailLetterRel",
                                                            "userRel",
                                                            "openShopMainProcessRel.checkAcceptRel"
                                                        ]);
                                                    }
                                                ])
                                                ->first();

        $trainingOrderCount       = $trainingPlan->orderRel->count();
        $trainingFinishOrderCount = $trainingPlan->orderRel->whereIn("status",
            [CollegeTrainingOrderModel::STATUS_FINISH, CollegeTrainingOrderModel::STATUS_CLOSE]
        )->count();

        if ($trainingOrderCount == $trainingFinishOrderCount && $trainingOrderCount > 0) {
            $shopIds        = $trainingPlan->orderRel->where("status", CollegeTrainingOrderModel::STATUS_FINISH)
                                                     ->pluck("studentShopId")->toArray();
            $remoteShopInfo = collect(
                RmsShopRemote::getShopInfoByIds($shopIds, ["id", "shopCode", "name", "province"])["shopList"]
            )->keyBy("id");


            $templateParamsGroup = [
                "title"         => $trainingPlan->name,
                "start"         => formatDateYmd($trainingPlan->planStartTime),
                "end"           => formatDateYmd($trainingPlan->planEndTime),
                "role"          => "",
                "username"      => "",
                "trainingOrder" => [],
            ];
            $pushUserGroup       = [];
            $trainingPlan->orderRel->where("status", CollegeTrainingOrderModel::STATUS_FINISH)->each(
                function (CollegeTrainingOrderModel $trainingOrderModel) use (
                    $remoteShopInfo,
                    &$templateParamsGroup,
                    &$pushUserGroup
                ) {
                    $trainingOrderUser = $trainingOrderModel->userRel->map(function (
                        CollegeTrainingOrderUserModel $trainingOrderUserModel
                    ) {
                        $rmsUser  = current(RmsUserRemote::getRmsUserByIds([$trainingOrderUserModel->userId]));
                        $username = attributeGet($rmsUser, "username", "");
                        $comment  = attributeGet($trainingOrderUserModel, "comment", "无");
                        return [
                            "userId"      => $trainingOrderUserModel->userId,
                            "userText"    => vsprintf(
                                "%s (%s分 %s分) \n",
                                [
                                    $username,
                                    $trainingOrderUserModel->examActualScore,
                                    $trainingOrderUserModel->practiceScore
                                ]
                            ),
                            "commentText" => vsprintf(
                                "%s (%s) \n",
                                [$username, empty($comment) ? "无" : $comment]
                            )
                        ];
                    });

                    $trainingOrder = [
                        "result"             => $trainingOrderModel->result,
                        "portrait"           => empty($trainingOrderModel->portrait) ? "无" : $trainingOrderModel->portrait,
                        "shopName"           => "",
                        "managerName"        => "",
                        "userText"           => $trainingOrderUser->implode("userText"),
                        "commentText"        => $trainingOrderUser->implode("commentText"),
                        "resourceFailLetter" => $trainingOrderModel->resourceFailLetterRel->isNotEmpty() ? "已上传" : "无",
                        "roleType-1"         => 0,
                        "roleType-2"         => 0
                    ];

                    if ($remoteShopInfo->offsetExists($trainingOrderModel->studentShopId)) {
                        $shopInfo           = $remoteShopInfo->offsetGet($trainingOrderModel->studentShopId);
                        $organizationManage = OrganizationManageService::getOrganizationInfoByProvinceCodeCode($shopInfo["province"]);
                        array_push($pushUserGroup, [
                            "shopId"       => $shopInfo["id"],
                            "provinceCode" => $shopInfo["province"],
                            "role"         => "省总",
                            "roleType"     => 1,
                            "username"     => $organizationManage->operationName,
                            "uid"          => $organizationManage->operationUid
                        ]);
                        $trainingOrder["shopName"]   = vsprintf(
                            "%s 夸父炸串 （%s）",
                            [$shopInfo["shopCode"], $shopInfo["name"]]
                        );
                        $trainingOrder["roleType-1"] = $organizationManage->operationUid;
                    }

                    $checkAccept = attributeGet($trainingOrderModel,
                        "openShopMainProcessRel.checkAcceptRel", null);

                    if ($checkAccept) {
                        array_push($pushUserGroup, [
                            "role"     => "督导",
                            "roleType" => 2,
                            "username" => $checkAccept->managerName,
                            "uid"      => $checkAccept->managerId
                        ]);
                        $trainingOrder["managerName"] = $checkAccept->managerName;
                        $trainingOrder["roleType-2"]  = $checkAccept->managerId;
                    }

                    array_push($templateParamsGroup["trainingOrder"], $trainingOrder);
                }
            );


            $pushUserCollection = collect($pushUserGroup)->unique();
            $rmsUser            = collect(RmsUserRemote::getRmsUserByIds(
                $pushUserCollection->pluck("uid")->toArray())
            )->keyBy("id");

            $pushUserCollection->each(function (array $user) use ($templateParamsGroup, $rmsUser) {
                $trainingOrder = collect($templateParamsGroup["trainingOrder"])
                    ->where("roleType-{$user['roleType']}", $user["uid"]);
                if ($rmsUser->offsetExists($user["uid"]) && $trainingOrder->isNotEmpty()) {

                    $userDetail          = $rmsUser->offsetGet($user["uid"]);
                    $msgTemplateContents = view()->file(app_path(
                            "Remote/Feishu/FsTemplate/College") . "/FinishTrainingPlanMsg.blade.php",
                        array_merge($templateParamsGroup, $user, [
                            "username"      => $userDetail["username"],
                            "trainingOrder" => $trainingOrder->toArray(),
                            "rate"          => number_format($trainingOrder->where("result", 1)
                                                                           ->count() / $trainingOrder->count(), 2) * 100
                        ])
                    )->render();

                    FeishuMsgRemote::getInstance()->sendInteractiveMsg(
                        $msgTemplateContents,
//                        "c32e1b91"
                        $rmsUser->offsetGet($user["uid"])["feishuUserId"]
                    );
                }
            });
        }

    }
}
